const { pool, add, edit } = require('./baseModel.js')

exports.add = async (fields) => {
    return await add('food_info', fields)
}

exports.edit = async (id, fields) => {
    return await edit('food_info', fields, { id })
}

exports.delete = async (id) => {
    return edit('food_info', { isDel: 1 }, { id })
}

exports.check = async (food_name) => {
    let result = await pool.query('select * from food_info where food_name=? and isDel=0', [food_name])
    return result[0]
}

exports.find = async (id) => {
    let result = await pool.query('select * from food_info where id=? and isDel=0', [id])
    return result[0]
}

exports.getTotalCount = async () => {
    let result = await pool.query('select count(*) as total from food_info where isDel=0')
    return result[0]
}

exports.findByPage = async (query) => {
    let sql = 'select * from food_info where 1 '
    let data = []
    if (query.food_name) {
        sql += `and food_name like ? `
        data.push('%' + query.food_name + '%')
    }
    if (query.category_name) {
        const CategoryModel = require('./category')
        let category_info = await CategoryModel.check(query.category_name)
        // console.log(category_info);
        if (category_info.length != 0) {
            sql += `and cid=? `
            data.push(category_info[0].id)
        }
    }
    sql += `and isDel=0 order by id limit ?,10`
    data.push((query.pageIndex - 1) * 10)
    // console.log(sql);
    // console.log(data);
    let result = await pool.query(sql, data)
    // console.log(result[0]);
    return result[0]
}

exports.uploadFoodImg = async (files) => {
    // console.log(files.food_img.name);
    const fs = require('fs')
    let name = Date.now() + '_' + files.food_img.name
    fs.writeFileSync(uploads + name, fs.readFileSync(files.food_img.path))
    return '/uploads/' + name;
}